package com.sihai.ehr.service.impl;

import java.text.MessageFormat;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.sihai.core.DataAccessor;
import com.sihai.core.DynamicQuery;
import com.sihai.core.Limit;
import com.sihai.core.LimitedList;
import com.sihai.core.QueryCreator;
import com.sihai.core.Sorter;
import com.sihai.ehr.model.biz.EmployeeinfoLog;
import com.sihai.ehr.model.biz.ExamStatistics;
import com.sihai.ehr.service.EmployeeinfoLogService;

/**
 * 员工变动信息日志服务实现类
 * 
 * @author henry
 * 
 */
@Service("employeeinfoLogService")
public class EmployeeinfoLogServiceImpl implements EmployeeinfoLogService {
	@Resource
	private DataAccessor dataAccessor;

	@Override
	public EmployeeinfoLog getEmployeeinfoLog(Long id) {
		if (id == null) {
			return null;
		}

		return dataAccessor.get(EmployeeinfoLog.class, id);
	}

	@Override
	public LimitedList<EmployeeinfoLog> searchEmployeeinfoLogs(final Long workId,
			Limit limit, Sorter sorter) {
		if (workId == null || workId <= 0) {
			throw new RuntimeException("【传入参数非法】【workId为空】");
		}
		try {
			return dataAccessor.findByQuery(EmployeeinfoLog.class,
					new QueryCreator() {
						@Override
						public Query createQuery(Session session) {
							DynamicQuery dynamicQuery = new DynamicQuery(
									"from EmployeeinfoLog e where 1<>2");
							dynamicQuery.appendIfNotNull(
									" and e.employeeinfoWork.id = :workId",
									"workId", workId);

							return dynamicQuery.build(session);
						}
					}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException(
					"【异常原因：获取员工日志列表时数据库发生异常】【异常说明：+"
							+ e.getMessage()
							+ "】【发生地点：EmployeeinfoLogServiceImpl.searchEmployeeinfoLogs;参数workId="
							+ workId + "】");
		}
	}

	@Override
	public void saveEmployeeinfoLog(EmployeeinfoLog employeeinfoLog) {
		if (employeeinfoLog == null) {
			throw new RuntimeException("【传入参数非法】【employeeinfoLog为空】");
		}
		try {
			dataAccessor.saveOrUpdate(employeeinfoLog);
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：保存考核统计到数据库发生异常】【异常说明："
					+ e.getMessage()
					+ "】【发生地点：EmployeeinfoLogServiceImpl.saveEmployeeinfoLog】");
		}
	}

	@Override
	public void removeEmployeeinfoLog(final String employeebaseinfoLogIds) {
		if (employeebaseinfoLogIds == null || employeebaseinfoLogIds.isEmpty()) {
			throw new RuntimeException("【参数异常：employeebaseinfoLogIds为空】");
		}
		try {
			dataAccessor.batchUpdate(new QueryCreator() {
				@Override
				public Query createQuery(Session session) {
					return session.createQuery(MessageFormat
							.format("delete from EmployeeinfoLog e where id in ({0})",
									employeebaseinfoLogIds));
				}
			});
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：移出考核强制分布设置数据库发生异常】【异常说明："
					+ e.getMessage()
					+ "】【发生地点：EmployeeinfoLogServiceImpl.removeEmployeeinfoLog】");
		}

	}

}
